package com.hams.demo.system.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.hams.demo.common.util.ExtAjaxResponse;
import com.hams.demo.system.entity.User;
import com.hams.demo.system.entity.dto.UserDTO;

import com.hams.demo.system.service.IUserService;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private IUserService userService;
	
	@RequestMapping("/saveOrUpdate")
	public @ResponseBody String saveOrUpdate(User user) 
	{
		try {		
			   userService.saveOrUpdate(user);
			   return "success";
		} catch (Exception e) {
			return "error";
		}		
	}
	
	@RequestMapping("/delete")
	public @ResponseBody ExtAjaxResponse delete(@RequestParam Long id) 
	{
		try {	
			User user =  userService.findOne(id);				
			if(null!=user) {
				user.setDepartment(null);
				userService.saveOrUpdate(user);
				userService.delete(user);
			}
			return new ExtAjaxResponse(true,"操作成功！");
		} catch (Exception e) {
			return new ExtAjaxResponse(false,"操作失败！");
		}
	}
	
	@RequestMapping("/findOne")
	public @ResponseBody UserDTO findOne(@RequestParam Long id) 
	{
			User user = userService.findOne(id);
			UserDTO dto = new UserDTO();		
			dto.setUserName(user.getUserName());
			dto.setPassword(user.getPassword());
			dto.setName(user.getDepartment().getName());						
			return dto;
	
	}
	
	@RequestMapping("/findAll")
	public @ResponseBody List<User> findAll() 
	{
		 List<User> lists =  userService.findAll();		
		return lists;
	}
	
	
}
